package doan.chuyennganh.fragment;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import doan.chuyennganh.activity.ExportActivity;
import doan.chuyennganh.activity.HomeActivity;
import doan.chuyennganh.activity.ListStudentActivity;
import doan.chuyennganh.activity.R;
import doan.chuyennganh.activity.ScannerActivity;
import doan.chuyennganh.activity.SlidingActivity;
import doan.chuyennganh.activity.SlidingMenuActivity;
import doan.chuyennganh.base.RequestUI;
import doan.chuyennganh.model.ClassStudent;
import doan.chuyennganh.model.ListClass;
import doan.chuyennganh.model.ListClassReturnObject;
import doan.chuyennganh.model.ListStudent;
import doan.chuyennganh.model.ListStudentReturnObject;
import doan.chuyennganh.model.Student;
import doan.chuyennganh.util.EncodeHelper;
import doan.chuyennganh.util.ListStudentDataSource;
import doan.chuyennganh.util.Constants;
import doan.chuyennganh.util.ListClassDataSource;
import doan.chuyennganh.util.SearchingHelper;

public class LeftMenuListFragment extends Fragment {
	private ListView lvClass;
	public static int selectedClass = 0;
	//private ListClass listClass;
	private ArrayList<String> listclassStrings;
	private SlidingMenuActivity activity = null;
	private Button btnUpdate;
	private ImageView ivSearch;
	private EditText edtFindString;
	private ArrayAdapter<String> lvAdapter;
	private ProgressDialog p;
	private ListClassDataSource databaseHelper;
	private ListStudentDataSource classHelper;
	private static int noClass = 0;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.layout_left_menu, container,
				false);
		lvClass = (ListView) rootView.findViewById(R.id.lstclass);
		btnUpdate = (Button) rootView.findViewById(R.id.btn_update_class_list);
		ivSearch = (ImageView) rootView.findViewById(R.id.search_edittext_imv);
		edtFindString = (EditText) rootView.findViewById(R.id.search_editext);
		ivSearch.setOnClickListener(layoutClick);
		btnUpdate.setOnClickListener(layoutClick);
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		activity = (SlidingActivity) getActivity();
		init();
	}

	@SuppressWarnings("unchecked")
	public void init() {
		if (activity != null) {
			//listClass = ListClass.getInstance();
			Intent intent = getActivity().getIntent();
			if (intent != null) {
				try {
					Bundle data = intent.getExtras();
					if (data != null) {
						ListClass.getInstance().setList((ArrayList<ClassStudent>) data
								.getSerializable(Constants.KEY_LIST_CLASS));
						showListClass();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
	}

	private OnClickListener layoutClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			activity = (SlidingMenuActivity) getActivity();
			switch (v.getId()) {
			case R.id.btn_update_class_list:
				btnUpdate.setEnabled(false);
				showProgressDialog();
				String userName = activity.pre.getString(
						Constants.PREFERENCE_USER_NAME, "");
				String passWord = activity.pre.getString(
						Constants.PREFERENCE_PASS_WORD, "");
				Logon logon = new Logon(Constants.LOGON_REQUEST, activity,
						EncodeHelper.changeText(userName),
						EncodeHelper.changeText(passWord));
				activity.getRequestQueue().addRequest(logon);
				break;
			case R.id.search_edittext_imv:
				SearchingHelper.ApproximatString(edtFindString.getText().toString(), ListClass.getInstance());

				// reload content
				lvAdapter.clear();
				listclassStrings = new ArrayList<String>();
				for (int i = 0; i < ListClass.getInstance().getAllClass().size(); i++) {
					listclassStrings.add(ListClass.getInstance().getAllClass().get(i)
							.getTenmonhoc().toString()
							+ "\n("
							+ ListClass.getInstance().getAllClass().get(i).getMalop()
									.toString() + ")");
				}
				lvAdapter.addAll(listclassStrings);
				lvAdapter.notifyDataSetChanged();
				lvClass.refreshDrawableState();

				break;
			default:
				break;
			}

		}
	};

	private void showListClass() {
		if (ListClass.getInstance().getAllClass().size() > 0) {
			listclassStrings = new ArrayList<String>();
			for (int i = 0; i < ListClass.getInstance().getAllClass().size(); i++) {
				listclassStrings.add(ListClass.getInstance().getAllClass().get(i)
						.getTenmonhoc().toString()
						+ "\n("
						+ ListClass.getInstance().getAllClass().get(i).getMalop().toString()
						+ ")");
			}
			lvAdapter = new ArrayAdapter<String>(activity, R.layout.list_item,
					listclassStrings);
			lvClass.setAdapter(lvAdapter);
			lvClass.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {

					if (ListClass.getInstance().getAllClass().size() > 0) {
						classHelper = new ListStudentDataSource(activity,
								ListClass.getInstance().getAllClass().get(position)
										.getMalop());
						classHelper.openForReadOnly();
						ListStudent.getInstance().setList(
								(ArrayList<Student>) classHelper
										.getAllStudents());
						ListStudent.getInstance().setClassID(
								ListClass.getInstance().getAllClass().get(position)
										.getMalop());
						ListStudent.getInstance().setAttendanceList(
								classHelper.getAllttendances());
						classHelper.close();
					}
					TextView tv = (TextView) activity
							.findViewById(R.id.tab_title);
					tv.setText(ListClass.getInstance().getAllClass().get(position)
							.getTenmonhoc().toString()
							+ "\n("
							+ ListClass.getInstance().getAllClass().get(position).getMalop()
									.toString() + ")");

					if (selectedClass != position
							&& SlidingActivity.currentTabActivity != null) {
						if (SlidingActivity.currentTabActivity instanceof ExportActivity) {
							((ExportActivity) SlidingActivity.currentTabActivity)
									.init();
						} else if (SlidingActivity.currentTabActivity instanceof ListStudentActivity) {
							((ListStudentActivity) SlidingActivity.currentTabActivity)
									.init();
						} else if (SlidingActivity.currentTabActivity instanceof HomeActivity) {
							((HomeActivity) SlidingActivity.currentTabActivity)
									.init();
						} else if (SlidingActivity.currentTabActivity instanceof ScannerActivity) {
							((ScannerActivity) SlidingActivity.currentTabActivity)
									.init();
						}
					}
					selectedClass = position;
					activity.getSlidingMenu().toggle();
				}
			});
		}

	}

	private void showProgressDialog() {
		p = new ProgressDialog(activity);
		p.setMessage(getString(R.string.txt_loading));
		p.setCancelable(false);
		p.show();
	}

	private void stopProgressDialog() {
		if (p != null && p.isShowing()) {
			p.dismiss();
			p = null;
		}
	}

	private void saveListClassData(ArrayList<ClassStudent> list, String userName) {
		if (list == null) {
			return;
		}
		databaseHelper = new ListClassDataSource(activity, userName);
		databaseHelper.open();
		for (ClassStudent cls : list) {
			databaseHelper.insertClass(cls);
		}
		databaseHelper.close();
	}

	private void saveStudentData(ArrayList<Student> listStudent,
			String tableName) {
		classHelper = new ListStudentDataSource(activity, tableName);
		classHelper.open();
		for (Student st : listStudent) {
			classHelper.insertStudent(st);
		}
		classHelper.close();
	}

	class Logon extends RequestUI {
		private String meesage = getString(R.string.txt_login_online_failed);
		private String userName = "";
		private String passWord = "";
		private ListClassReturnObject list;

		public Logon(Object key, Activity activity, String userName,
				String passWord) {
			super(key, activity);
			this.userName = userName;
			this.passWord = passWord;
		}

		@Override
		public void execute() throws Exception {
			list = activity.daApi.Login(userName, passWord);
		}

		@Override
		public void executeUI(Exception ex) {

			btnUpdate.setEnabled(true);
			if (list != null && list.getData() != null) {
				ListClass.getInstance().setList(list.getData());
				saveListClassData(list.getData(), userName);
				int i = 0;
				for (ClassStudent cls : list.getData()) {
					i++;
					GetListStudent get = new GetListStudent(
							Constants.LIST_STUDENT_REQUEST, activity,
							cls.getMalop(), i);
					activity.getRequestQueue().addRequest(get);
				}
				meesage = list.getMessage();

			} else {
				stopProgressDialog();
				Toast.makeText(activity, meesage, Toast.LENGTH_LONG).show();
			}
		}
	}

	class GetListStudent extends RequestUI {
		private String meesage = getString(R.string.txt_get_list_student_failed);
		private String malop = "";
		private int index = 0;
		private ListStudentReturnObject list;

		public GetListStudent(Object key, Activity activity, String malop,
				int index) {
			super(key, activity);
			this.malop = malop;
			this.index = index;
		}

		@Override
		public void execute() throws Exception {
			list = activity.daApi.GetListStudent(malop);
		}

		@Override
		public void executeUI(Exception ex) {
			noClass++;

			btnUpdate.setEnabled(true);
			if (list != null) {
				meesage = list.getMessage();
				saveStudentData(list.getData(), malop);
			} else {
				stopProgressDialog();
				Toast.makeText(activity, meesage, Toast.LENGTH_LONG).show();
			}
			if (noClass >= index) {
				stopProgressDialog();
				// reload content
				lvAdapter.clear();
				listclassStrings = new ArrayList<String>();
				for (int i = 0; i < ListClass.getInstance().getAllClass().size(); i++) {
					listclassStrings.add(ListClass.getInstance().getAllClass().get(i)
							.getTenmonhoc().toString()
							+ "\n("
							+ ListClass.getInstance().getAllClass().get(i).getMalop()
									.toString() + ")");
				}
				lvAdapter.addAll(listclassStrings);
				lvAdapter.notifyDataSetChanged();
				lvClass.refreshDrawableState();
				classHelper = new ListStudentDataSource(activity, ListClass.getInstance()
						.getAllClass().get(selectedClass).getMalop());
				classHelper.openForReadOnly();
				ListStudent.getInstance().setList(
						(ArrayList<Student>) classHelper.getAllStudents());
				ListStudent.getInstance().setClassID(
						ListClass.getInstance().getAllClass().get(selectedClass).getMalop());
				ListStudent.getInstance().setAttendanceList(
						classHelper.getAllttendances());
				classHelper.close();
				if (SlidingActivity.currentTabActivity != null) {
					if (SlidingActivity.currentTabActivity instanceof ExportActivity) {
						((ExportActivity) SlidingActivity.currentTabActivity)
								.init();
					} else if (SlidingActivity.currentTabActivity instanceof ListStudentActivity) {
						((ListStudentActivity) SlidingActivity.currentTabActivity)
								.init();
					} else if (SlidingActivity.currentTabActivity instanceof HomeActivity) {
						((HomeActivity) SlidingActivity.currentTabActivity)
								.init();
					} else if (SlidingActivity.currentTabActivity instanceof ScannerActivity) {
						((ScannerActivity) SlidingActivity.currentTabActivity)
								.init();
					}
				}

			}
		}
	}
}
